import { constantRoutes } from "@/router/index.js"
import { getInfo } from "@/api/user"
// import { removeToken } from "@/utils/auth"
import Layout from "@/layout"

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

export function filterAsyncRoutes(arr) {
  const res = []
  let obj = {}
  // arr.forEach((el) => {
  //   obj = {
  //     path: "/" + el.activeMenu,
  //     component: Layout,
  //     hidden: false,
  //     redirect: "/" + el.activeMenu,
  //     children: [
  //       {
  //         path: el.activeMenu,
  //         name: el.activeMenu,
  //         component: loadView(el.menuPath),
  //         meta: {title: el.menuName, icon: el.menuIcon}
  //       }
  //     ]
  //   }
  //   res.push(obj)
  // })
// return res

  let obj2 = {
    path: "/",
    component: Layout,
    hidden: false,
    redirect: {name: 'home'},
    children: []
  }

  for (let i = 0; i < arr.length; i++) {
    if (i == 0) {
      obj = {
        path: arr[i].activeMenu,
        name: 'home',
        hidden: true,
        component: loadView(arr[i].menuPath),
        meta: {title: arr[i].menuName, icon: arr[i].menuIcon, activeIcon: arr[i].createBy}
      }
    } else {
      obj = {
        path: arr[i].activeMenu,
        name: arr[i].activeMenu,
        hidden: true,
        component: loadView(arr[i].menuPath),
        meta: {title: arr[i].menuName, icon: arr[i].menuIcon, activeIcon: arr[i].createBy}
      }
    }
    res.push(obj)
  }
  obj2.children = res

  return [obj2]
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

const state = {
  routes: [],
  addRoutes: [],
  buttonList: [],
  routeLen: 3
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    state.routeLen = constantRoutes.concat(routes).length
  },
  RESET_STATUS: (state) => {
    state.routes = []
    state.addRoutes = []
    state.buttonList = []
    state.routeLen = 3
  }
}

const actions = {
  generateRoutes({commit}) {
    const userCode = sessionStorage.getItem("userCode")
    return new Promise((resolve) => {
      getInfo(userCode).then((res) => {
        const accessedRoutes = filterAsyncRoutes(res.object)
        commit("SET_ROUTES", accessedRoutes)
        resolve(accessedRoutes)
      }).catch(err => {
        console.log(err)
      })
    })
  },
  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      // removeToken()
      sessionStorage.clear()
      commit("RESET_STATUS")
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
